//
//  YTStudyOneTableViewCell.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/11/13.
//

#import "YTStudyOneTableViewCell.h"


@interface YTStudyOneTableViewCell ()

@property (nonatomic ,strong) UILabel * title;

@property (nonatomic ,strong) UILabel * createTime;
@property (nonatomic ,strong) UILabel * author;
@property (nonatomic ,strong) UIImageView * learnFile;
@property (nonatomic ,strong) UIImageView * bfimg;

@end

@implementation YTStudyOneTableViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        [self setupView];
    }
    return self;
}


- (void)setupView{
    
    self.backgroundColor = UIColor.clearColor;
    self.contentView.backgroundColor = UIColor.clearColor;
    self.userInteractionEnabled = YES;
    self.contentView.userInteractionEnabled = YES;
    
    UIView * backview = [UIView new];
    backview.backgroundColor = UIColor.whiteColor;
    [self.contentView addSubview:backview];
    [DTKTool YJ:kwt(5) andView:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.bottom.offset(kwt(-10));
    }];
    UILabel * title = [DTKTool labelWithText:@"--" andFont:kCFont(16) andTextColor:KcolorHex(@"#222222")];
    title.numberOfLines = 2;
    self.title = title;
    [backview addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(10));
        make.top.offset(kwt(15));
    }];
    
    UILabel * createTime = [DTKTool labelWithText:@"--" andFont:kFont(14) andTextColor:KcolorHex(@"#7D7D7D")];
    self.createTime = createTime;
    createTime.mas_KYS().mas_KLS();
    [backview addSubview:createTime];
    [createTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-120));
        make.top.offset(kwt(75));
    }];
    
    UILabel * author = [DTKTool labelWithText:@"--" andFont:kFont(14) andTextColor:KcolorHex(@"#222222")];
    self.author = author;
    author.textAlignment = NSTextAlignmentLeft;
    [backview addSubview:author];
    [author mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(10));
        make.right.equalTo(createTime.mas_left).offset(kwt(-10));
        make.centerY.equalTo(createTime);
    }];
    
    UIImageView * learnFile = kimageView(@"upload_photos");
    self.learnFile = learnFile;
    learnFile.clipsToBounds = YES;
    [backview addSubview:learnFile];
    [DTKTool YJ:kwt(4) andView:learnFile];
    [learnFile mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(kwt(75));
        make.centerY.offset(0);
        make.width.offset(kwt(95));
        make.right.offset(kwt(-10));
    }];
    MJWeakSelf
    learnFile.addClickBlock(^{
        [weakSelf openSP];
    });
    UIImageView * bfimg = kimageView(@"study_video_player");
    self.bfimg = bfimg;
    [learnFile addSubview:bfimg];
    [bfimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.offset(kwt(30));
        make.center.offset(0);
    }];
}

- (void)setModel:(YTStashTJModel *)model{
    _model = model;
  
    self.title.text = model.title;
    self.createTime.text = [NSDate br_stringFromDate:[NSDate br_dateFromString:model.createTime dateFormat:@"yyyy-MM-dd HH:mm:ss"]  dateFormat:@"yyyy-MM-dd"];

    self.author.text = model.author;
    if([model.displayForm isEqualToString:@"1"]){/////展示形式 1:视频 2:图文
        self.bfimg.hidden = NO;
        self.learnFile.hidden = NO;
        if(model.coverImageUrl.length > 0){
            [self.learnFile LZsetImageWithImagePath:model.coverImageUrl placeholderImage:[UIImage imageNamed:@"upload_photos"]];
        } else if(model.learnFileImage.length > 0){
            [self.learnFile LZsetImageWithImagePath:model.learnFileImage placeholderImage:[UIImage imageNamed:@"upload_photos"]];
        } else {
            [self extractAndCacheFirstFrameFromVideo:[NSURL URLWithString:model.learnFileUrl] forImageView:self.learnFile];
        }
        [self.title mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.offset(kwt(255));
        }];
    } else if([model.displayForm isEqualToString:@"2"]){
        if(model.coverImageUrl.length > 0){
            self.bfimg.hidden = YES;
            self.learnFile.hidden = NO;
            [self.learnFile LZsetImageWithImagePath:model.coverImageUrl placeholderImage:[UIImage imageNamed:@"upload_photos"]];
            [self.title mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.offset(kwt(255));
            }];
        } else {
            self.bfimg.hidden = YES;
            self.learnFile.hidden = YES;
            [self.title mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.offset(kwt(355));
            }];
        }
    }
}

// 提取视频第一帧的函数
- (void)extractAndCacheFirstFrameFromVideo:(NSURL *)videoURL forImageView:(UIImageView *)imageView {
    imageView.image = [UIImage imageNamed:@"upload_photos"];
    SDImageCache *imageCache = [SDImageCache sharedImageCache];
    UIImage * img = [imageCache imageFromMemoryCacheForKey:videoURL.absoluteString];
    if(img){
        imageView.image = img;
        return;
    }
    img = [imageCache imageFromDiskCacheForKey:videoURL.absoluteString];
    if(img){
        imageView.image = img;
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVAsset *asset = [AVAsset assetWithURL:videoURL];
        AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        generator.maximumSize = CGSizeMake(300, 300); // 可以设置最大尺寸以优化性能
        generator.appliesPreferredTrackTransform = YES;
        CMTime time = CMTimeMakeWithSeconds(0, asset.duration.timescale); // 获取第一帧
        AVAssetImageGeneratorCompletionHandler completionHandler = ^(CMTime requestedTime, CGImageRef imageRef, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
            if (result == AVAssetImageGeneratorSucceeded) {
                UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = thumbnail;
                    [imageCache storeImage:thumbnail forKey:videoURL.absoluteString completion:^{
                        NSLog(@"视频图片储存成功");
                    }];
                    
                });
            } else {
                NSLog(@"Failed to generate thumbnail: %@", error);
            }
        };
        
        [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:time]] completionHandler:completionHandler];
    });
}
- (void)openSP{
    if([self.model.displayForm isEqualToString:@"1"]){
        if(self.openvVideoBlock){
            self.openvVideoBlock(self.model.learnFileUrl);
        }
//        [DTKTool openImagAndVideo:@[self.model.learnFileUrl] andopenview:self.learnFile andIndex:0];
    } else {
        [DTKTool openImagAndVideo:@[self.model.coverImageUrl] andopenview:self.learnFile andIndex:0];
        
    }
}
@end
